﻿using AiQiuQuan.Sport.Core;
using AiQiuQuan.Sport.WebApi.Services;
using Microsoft.AspNetCore.Mvc;

namespace AiQiuQuan.Sport.WebApi.Controllers
{
    /// <summary>
    /// 页面控制器
    /// </summary>
    [Route("v2/[controller]/")]
    public class PageController : Controller
    {
        private readonly ApiUrl _apiUrl;
        private readonly IWxCallbackService _wxCallbackService;
        private readonly IAccessTokenService _accessTokenService;

        /// <summary>
        /// ctor
        /// </summary>
        public PageController(
            ApiUrl apiUrl,
            IWxCallbackService wxCallbackService,
            IAccessTokenService accessTokenService)
        {
            _apiUrl = apiUrl;
            _wxCallbackService = wxCallbackService;
            _accessTokenService = accessTokenService;
        }

        /// <summary>
        /// 用户实名认证
        /// </summary>
        /// <param name="scope">snsapi_base(默认)、snsapi_userinfo</param>
        /// <param name="attachData">授权成功重定向参数，可以填写a-zA-Z0-9的参数值，最多128字节</param>
        [HttpGet("wx_authenticate")]
        [DisabeUnaryResult]
        public async Task<IActionResult> WxAuthenticateAsync(string scope = "snsapi_userinfo", string attachData = "")
        {
            var url = await _accessTokenService.GetWxWebAuthorizeUrlAsync($"{_apiUrl.BaseUrl}v2/page/wx_authenticate_result", scope, attachData);
            ViewBag.url = url;
            return View("WxAuthenticate");
        }

        /// <summary>
        /// 微信公众号授权回调
        /// </summary>
        /// <param name="code">code</param>
        /// <param name="state">附加参数</param>
        [HttpGet("wx_authenticate_result")]
        [DisabeUnaryResult]
        public async Task<IActionResult> WxAuthenticateResultAsync(string code, string state)
        {
            await _wxCallbackService.AuthenticateAsync(code, state);
            var jssdkConfig = await _accessTokenService.GetWxJsSdkConfigAsync($"{_apiUrl.BaseUrl}v2/page/wx_authenticate_result");
            ViewBag.status = 1;
            ViewBag.jsconfig = System.Text.Json.JsonSerializer.Serialize(jssdkConfig);
            return View("WxAuthenticateResult");
        }
    }
}
